//
//  PywUserViewController.m
//  PywSdk
//
//  Created by smallwave on 16/8/10.
//  Copyright © 2016年 zero. All rights reserved.
//

#import "PywUserViewController.h"
#import "PywMasonry.h"
#import "UILabel+Pyw.h"
#import "PywUserCenterFooterView.h"
#import "PywUserCenterCell.h"
#import "PywPlatformMain.h"
#import "PywUserCenterApi.h"
#import "PywUserCenterModel.h"
#import "PywMBProgressHUD+Pyw.h"

#import "PywModifyLoginPwdViewController.h"
#import "PywAccountManagerViewController.h"

#import "ShowCouponsController.h"
#import "PywBindGetSMSCodeController.h"
#import "ApiClientConst.h"
// “交易密码”跳Web端的控制器导入
#import "PywReviseTradePwdController.h"
#import "PywTradePWDController.h"
#import "PywAppInfo.h"
#import "PywUserListModel.h"
#import "PywRealNameAuthModel.h"

#import "PywIAPHelper.h"

@interface PywUserViewController ()<UITableViewDelegate, UITableViewDataSource, PywUserCenterCellDelegate>

@property (nonatomic, strong) UITableView           *tableView;
@property (nonatomic,strong) NSMutableArray         *listModelArray;//数组列表
@property (nonatomic, strong) PywUserCenterApi      *userCenterApi; // 用户中心接口请求
@property (nonatomic, strong) PywUserCenterModel    *userInfo;      // 存储用户中心返回的数据模型
@property (nonatomic, strong) PywRealNameAuthModel  *realNameAuthModel; // 用户实名制信息
@end

@implementation PywUserViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Life Cycle Method
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUp];
    
}

#pragma mark - PrepareUI
- (void)setUp{
    
    self.title = @"用户中心";
    NSString *version = [NSString stringWithFormat:@"V%@",[PywAppInfo sharedAppInfo].verID];
    UILabel *versionLabel = [UILabel labelWithText:version
                                     textAlignment:NSTextAlignmentRight
                                          fontSize:13
                                         textColor:RGB(153, 153, 153, 1)];
    versionLabel.frame = CGRectMake(0, 0, 80, 40);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:versionLabel];
    
    
    [self addSubviewAndLayoutSubviews];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reloadUserCenter:)
                                                 name:ReloadUserCenterData
                                               object:nil];
}
- (void)addSubviewAndLayoutSubviews
{
    [self.view addSubview:self.tableView];
    
    [self.tableView mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.top.left.bottom.right.offset(0);
    }];
    
    [self requestUserCenterApi];
    
}

- (void)setUpModelContents
{
    [self.listModelArray removeAllObjects];
    
    PywUserListModel *model_1 = [self listModelWithTitle:[NSString stringWithFormat:@"欢迎您，%@",self.userInfo.account]
                                                 value:[PywPlatformMain sharedPlatformMain].userName
                                              listType:ListType_account
                                         accessibilityId:@""];
    [self.listModelArray addObject:[NSArray arrayWithObject:model_1]];
    if (![PywAppInfo sharedAppInfo].is_applepay) {
        NSString *coupon = [self.userInfo.coupon_count integerValue] >0 ? [NSString stringWithFormat:@"%@张可用",self.userInfo.coupon_count]:@"无可用代金券";
        PywUserListModel *model_2 = [self listModelWithTitle:@"查看代金券"
                                                       value:coupon
                                                    listType:ListType_coupon
                                             accessibilityId:@"center_voucher"];
        
        PywUserListModel *model_3 = [self listModelWithTitle:@"登录密码"
                                                       value:@"修改"
                                                    listType:ListType_loginPwd
                                             accessibilityId:@"center_loginpwsd"];
        
        NSString *payPassword = [self.userInfo.have_pay_pwd integerValue] == 0 ? @"未设置" : @"";
        payPassword = [PywPlatformMain sharedPlatformMain].accountType == UserType_Account?@"不可用":payPassword;
        PywUserListModel *model_4 = [self listModelWithTitle:@"交易密码"
                                                       value:payPassword
                                                    listType:ListType_payPwd
                                             accessibilityId:@"center_paypwsd"];
        NSArray *array = [NSArray arrayWithObjects:model_2,model_3,model_4, nil];
        [self.listModelArray addObject:array];
    }else {
        PywUserListModel *model = [self listModelWithTitle:@"登录密码"
                                                       value:@"修改"
                                                    listType:ListType_loginPwd
                                           accessibilityId:@"center_loginpwsd"];
        NSArray *array = [NSArray arrayWithObjects:model, nil];
        [self.listModelArray addObject:array];
    }
    
    
}

- (PywUserListModel *)listModelWithTitle:(NSString *)title
                                   value:(NSString *)value
                                listType:(ListType)listType
                         accessibilityId:(NSString *)accessibilityId
{
    PywUserListModel *model = [[PywUserListModel alloc] init];
    model.title = title;
    model.value = value;
    model.listType = listType;
    model.accessibilityId = accessibilityId;
    return model;
}

#pragma mark - Notification
/**
 *  重新刷新数据
 *
 *  @param aNotification <#aNotification description#>
 */
- (void)reloadUserCenter:(NSNotification *)aNotification
{
    [self requestUserCenterApi];
}

#pragma mark - Data Processing
/**
 *  发送请求用户中心
 */
- (void)requestUserCenterApi
{
    WEAK_SELF;
    [self.userCenterApi requestUserCenterWithSuccess:^(NSString *status, id anyObjct) {
        STRONG_SELF(weakSelf);
        strongSelf.userInfo = anyObjct;
        strongSelf.realNameAuthModel = [[PywRealNameAuthModel alloc] initWithDict:strongSelf.userInfo.id_info];
        [PywPlatformMain sharedPlatformMain].is_have_pay_pwd = [strongSelf.userInfo.have_pay_pwd boolValue];
        [PywPlatformMain sharedPlatformMain].passport = strongSelf.userInfo.passport;
        [PywPlatformMain sharedPlatformMain].account = strongSelf.userInfo.account;
        [PywPlatformMain sharedPlatformMain].accountType = [strongSelf.userInfo.type integerValue];
        [PywPlatformMain sharedPlatformMain].is_verify = strongSelf.realNameAuthModel.is_verify;
        [strongSelf setUpModelContents];
        [strongSelf.tableView reloadData];
        
    } fail:^(NSError *error) {
        
    }];
}
#pragma mark - Actions
/**
 *  平台账号 登录修改交易密码【与旧版相同，跳Web端】
 */
- (void)selectPayPwdSkipDetail
{
    if ([self.userInfo.type integerValue] == UserType_Passport) {
        if ([PywPlatformMain sharedPlatformMain].is_have_pay_pwd) { //已经设置交易密码
            
            PywReviseTradePwdController *reviseTradePwdController = [[PywReviseTradePwdController alloc] init];
            reviseTradePwdController.wap_modify_paypwd_url = self.userInfo.wap_modify_paypwd_url;
            reviseTradePwdController.wap_forget_paypwd_url = self.userInfo.wap_forget_paypwd_url;
            [self.navigationController pushViewController:reviseTradePwdController animated:YES];
        } else { // 未设置交易密码
            PywTradePWDController *tradeVC = [[PywTradePWDController alloc] init];
            tradeVC.wap_set_paypwd_url = self.userInfo.wap_set_paypwd_url;
            [self.navigationController pushViewController:tradeVC animated:YES];
        }
    }else {
        [PywMBProgressHUD showError:@"请登陆平台账号修改交易密码！" toView:[UIApplication sharedApplication].keyWindow];
    }
}
#pragma mark - UITableViewDelegate & UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.listModelArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *array = self.listModelArray[section];
    return array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifiter = @"cell";
    PywUserCenterCell *cell = [tableView dequeueReusableCellWithIdentifier:identifiter];
    if (cell == nil) {
        cell = [[PywUserCenterCell alloc] initWithStyle:UITableViewCellStyleDefault
                                        reuseIdentifier:identifiter];
        cell.cellBtnDelegate = self;
    }
    PywUserListModel *listModel = self.listModelArray[indexPath.section][indexPath.row];
    cell.listModel = listModel;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    PywUserListModel *listModel = self.listModelArray[indexPath.section][indexPath.row];
    switch (listModel.listType) {
        case ListType_coupon:
        {
            ShowCouponsController *showCouponVC = [[ShowCouponsController alloc] init];
            [self.navigationController pushViewController:showCouponVC animated:YES];
        }
            break;
        case ListType_loginPwd:
        {
            PywModifyLoginPwdViewController *updateLoginPwdVC = [[PywModifyLoginPwdViewController alloc] init];
            [self.navigationController pushViewController:updateLoginPwdVC animated:YES];
        }
            break;
        case ListType_payPwd:
        {
            [self selectPayPwdSkipDetail];
        }
            break;
            
        default:
            break;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section != 0) {
        return 10;
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44;
}
#pragma mark - PywUserCenterCellDelegate

- (void)userCenterCell:(PywUserCenterCell *)userCenterCell
        SelectedButton:(UIButton *)btn
{
    PLog(@"%s",__FUNCTION__);
    if ([PywPlatformMain sharedPlatformMain].accountType == UserType_Passport) {
        PywAccountManagerViewController *accountManagerVC = [[PywAccountManagerViewController alloc] init];
        [self.navigationController pushViewController:accountManagerVC animated:YES];
    }else {
        PywBindGetSMSCodeController *getCodeView = [[PywBindGetSMSCodeController alloc] init];
        [self.navigationController pushViewController:getCodeView animated:YES];
    }
}

#pragma mark - Lazy Load
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.backgroundColor = RGB(232, 232, 232, 1);
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
        PywUserCenterFooterView *footerView = [[PywUserCenterFooterView alloc] initWithFrame:CGRectMake(0, 0, 0, 300)];
        _tableView.tableFooterView = footerView;
        
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

- (PywUserCenterApi *)userCenterApi
{
    if (!_userCenterApi) {
        _userCenterApi = [PywUserCenterApi manager];
    }
    return _userCenterApi;
}

/**
 *  列表数组
 */
- (NSMutableArray *)listModelArray
{
    if (!_listModelArray) {
        _listModelArray = [[NSMutableArray alloc] init];
    }
    return _listModelArray;
}

@end
